package stc.skymobi.netty.handler.codec.http.transformer;

import io.netty.handler.codec.http.FullHttpRequest;
import stc.skymobi.bean.kv.KVDecoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RestfulUrlTransformer implements HttpRequestTransformer {
    private KVDecoder decoder;
    private String requestCode;

    public Object transform(FullHttpRequest httpRequest) {
        Map<String,List<String>> params = new HashMap<String,List<String>>();
        for(String headerKey : httpRequest.headers().names()){
            params.put(headerKey,httpRequest.headers().getAll(headerKey));
        }
        
        String uri = httpRequest.getUri();
        int idx = uri.indexOf(requestCode);
        if(idx > -1){
            uri = uri.substring(idx+requestCode.length()+1);
            boolean odd = true;
            String key="";
            String value;
            for(String kv : uri.split("/")){
                if(odd){
                    key = kv;
                } else {
                    value = kv;
                    List<String> values = new ArrayList<String>();
                    values.add(value);
                    params.put(key,values);
                }
                odd = !odd;
            }
        }

        return  decoder.transform(params);
    }

    public void setDecoder(KVDecoder decoder) {
        this.decoder = decoder;
    }

    public String getRequestCode() {
        return requestCode;
    }

    public void setRequestCode(String requestCode) {
        this.requestCode = requestCode;
    }
}
